package core.threadpool;

public class PoolThread extends Thread{
	private PoolQueue<PoolThread> threadQueue; 
	private PoolQueue<Runnable> runQueue;
	private boolean isStop = false;
	private int coreSize;
	private long timeAlive;
	
	public PoolThread(PoolQueue<PoolThread> threadQueue, PoolQueue<Runnable> runQueue, int coreSize, long timeAlive){
		this.threadQueue = threadQueue;
		this.runQueue = runQueue;
		this.coreSize = coreSize;
		this.timeAlive = timeAlive;
		
	}
	
	@Override
	public void run() {
		while(!isStop){
			Runnable r = runQueue.dequeue();
			if (r == null) {
				try {
					synchronized (runQueue) {
						runQueue.wait(timeAlive);
						killOwn();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				continue;
			}
			r.run();
		}
		super.run();
	}
	
	public void stopRun() {
		isStop = true;
	}
	
	private void killOwn(){
		int runSize = runQueue.size();
		if (runSize < coreSize) {
			stopRun();
			threadQueue.remove(this);
		}
	}
}
